package com.yz.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yz.common.BaseContext;
import com.yz.common.R;
import com.yz.entity.User;
import com.yz.service.UserService;
import com.yz.utils.SMSUtils;
import com.yz.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        // 获取手机号
        String phone = user.getPhone();
        // 生成 4位随机数字
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        // 发送短信验证码
//        SMSUtils.sendMessage("",code,phone,"空");
        log.info("手机号：{}，你的验证码为：{}",phone,code);
        // 把phone(手机号),code（验证码）保存到Session中
        session.setAttribute("code",code);
        session.setAttribute("phone",phone);
        return R.success("短信已发送");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        // 获取手机号，code(验证码)
        String phone = (String) map.get("phone");
        String code = (String) map.get("code");
        // 获取Session中的code
        String codeSesion = (String) session.getAttribute("code");
        String phoneSesion = (String) session.getAttribute("phone");
        // 判断phone,code是否跟Session中的一样
        if(phoneSesion.equals(phone) && codeSesion.equals(code)){
            // 判断用户是否已经存在 ，不存在 则新建用用户
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getPhone,phone);
            User user = userService.getOne(wrapper);
            if(user == null){
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            // 保存用户id到Session和线程缓存中
            session.setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("验证码错误");
    }
}
